package tcss543;

import java.io.*;
import java.util.*;

public class GraphFileImporter {
	private BufferedReader reader;
	
	private int[] units;
	private double[] prices;
	
	public GraphFileImporter(String fileName) throws FileNotFoundException {
		reader = new BufferedReader(new FileReader(fileName));
	}
	
	public DeviceGraph Load() throws IOException {
		getNodes();
		int[] requestors = units;
		double[] bids = prices;
		getNodes();
		int[] helpers = units;
		double[] asks = prices;
		int[][] neighbors = getNeighbors(requestors.length);
		
		return new DeviceGraph(requestors, bids, helpers, asks, neighbors);
	}
	
	private void getNodes() throws NumberFormatException, IOException {
		String line;
		ArrayList<Integer> unitsList;
		ArrayList<Double> pricesList;
		
		unitsList = new ArrayList<Integer>();
		pricesList = new ArrayList<Double>();
		while ((line = reader.readLine()).length() != 0) {
			String[] up = line.split(":");
			unitsList.add(Integer.parseInt(up[0]));
			pricesList.add(Double.parseDouble(up[1]));
		}
		
		units = new int[unitsList.size()];
		prices = new double[pricesList.size()];
		
		for (int i = 0; i < unitsList.size(); i++) {
			units[i] = unitsList.get(i);
			prices[i] = pricesList.get(i);
		}
	}
	
	private int[][] getNeighbors(int requestorCount) throws IOException {
		ArrayList<ArrayList<Integer>> reqNeighbors = new ArrayList<ArrayList<Integer>>();
		for (int i = 0; i < requestorCount; i++) {
			reqNeighbors.add(new ArrayList<Integer>());
		}
		
		String line;
		
		while ((line = reader.readLine()) != null) {
			String[] rh = line.split(",");
			int r = Integer.parseInt(rh[0]);
			int h = Integer.parseInt(rh[1]);
			
			reqNeighbors.get(r - 1).add(h - 1);
		}
		
		int[][] neighbors = new int[requestorCount][];
		for (int i = 0; i < requestorCount; i++) {
			neighbors[i] = new int[reqNeighbors.get(i).size()];
			
			for (int j = 0; j < neighbors[i].length; j++) {
				neighbors[i][j] = reqNeighbors.get(i).get(j);
			}
		}
		
		return neighbors;
	}
}
